package com.ecarx.library_base.base_util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import androidx.annotation.RequiresApi;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class FileUtils {
    private static final String TAG = "FileUtils";

    public static boolean isSDCardAlive() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static long getSize(File file) {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File f : fileList) {
                if (f.isDirectory()) {
                    size = size + getSize(f);
                } else {
                    size = size + f.length();
                }
            }
        } catch (Exception ignore) {
        }
        return size;
    }

    /**
     * 格式化单位
     */
    public static String formatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return "0KB";
        }
        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }
        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }
        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }

    public static boolean delete(File file) {
        if (file == null) {
            return false;
        }
        if (file.isDirectory()) {
            String[] children = file.list();
            for (String c : children) {
                boolean success = delete(new File(file, c));
                if (!success) {
                    return false;
                }
            }
        }
        return file.delete();
    }


    public static boolean saveImage(Activity activity, View saveView) {
        Bitmap bitmap;
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "lifeim";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        bitmap = view.getDrawingCache();
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int[] location = new int[2];
        saveView.getLocationOnScreen(location);
        try {
            bitmap = Bitmap.createBitmap(bitmap, location[0], location[1], saveView.getWidth(), saveView.getHeight());
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            Uri uri = Uri.fromFile(file);
            activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.e("15151", "生成预览图片失败：" + e);
            return false;
        } catch (IllegalArgumentException e) {
            Log.e("15151", "width is <= 0, or height is <= 0");
            return false;
        } catch (IOException e) {
            Log.e("15151", "IO异常：" + e.getMessage());
            e.printStackTrace();
            return false;
        } finally {
            // 清理缓存
            view.destroyDrawingCache();
        }
        return true;
    }

    public static String writeToFile(Context context, String text, String fileName, String type) {
        String absFilePath = "";
        FileWriter fileWriter = null;
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String path = context.getDataDir().getPath() + File.separator + type;
                File dir = new File(path);
                if (!dir.exists()) {
                    boolean mkdirs = dir.mkdirs();
                    Log.d("FileUtils", "writeToFile.mkdirs=" + mkdirs);
                }
                File file = new File(path + File.separator + fileName);
                if (!file.exists()) { // TODO Auto-genera
                    file.createNewFile();
                }
                fileWriter = new FileWriter(file, false);
                absFilePath = file.getAbsolutePath();
                fileWriter.write(text);
            }
            Log.d("FileUtils", "absFilePath=" + absFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileWriter != null) {
                    fileWriter.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return absFilePath;
    }

    //把文件从一个地方复制到另一个地方
    public static boolean copyFile(File fromFile, File toFile) {

        FileInputStream fosfrom = null;
        FileOutputStream fosto = null;
        try {
            Log.d(TAG, "mCopyFile,step1");
            fosfrom = new FileInputStream(fromFile);
            Log.d(TAG, "mCopyFile,step1.1");
            fosto = new FileOutputStream(toFile);
            Log.d(TAG, "mCopyFile,step2");
            byte bt[] = new byte[1024 * 1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
                Log.d(TAG, "mCopyFile,step3");
            }
            Log.d(TAG, "mCopyFile,step4");
        } catch (FileNotFoundException e) {
            Log.i(TAG, "复制文件异常=" + e.getMessage());
            return false;
        } catch (IOException e) {
            Log.i(TAG, "复制文件异常=" + e.getMessage());
            return false;
        } finally {
            try {
                if (fosto != null) {
                    fosto.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fosfrom != null) {
                    fosfrom.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return true;
    }

    public static void limitFileSize(File file, int size) {
        if (file.exists() && file.isDirectory()) {
            if (file.listFiles() != null && file.listFiles().length > size) {
                File file1 = Arrays.stream(file.listFiles()).sorted(new Comparator<File>() {
                    @Override
                    public int compare(File o1, File o2) {
                        return o1.lastModified() > o2.lastModified() ? 1 : -1;
                    }
                }).collect(Collectors.toList()).get(0);
                boolean delete = file1.delete();
                if (delete) {
                    Log.i(TAG, "limitFileSize: " + file1.getName() + " isdelete");
                }

            }
        }
    }


    /**
     * @param rootPath  根目录
     * @param subPath   子目录目录
     * @param fileSuffixFilters 文件过滤，如 .apk、.xml，为null就遍历返回所有文件
     * @return 返回所有筛选的文件地址，地址不包含根目录
     */
    public static List<String> getFilteredFilePathWithOutParent(String rootPath, String subPath, List<String> fileSuffixFilters) {
        List<String> pathList = new ArrayList<>();
        File rootFile = new File(rootPath, subPath);
        if (!rootFile.exists() || !rootFile.isDirectory()) {
            return pathList;
        }
        filePathAppend(pathList, rootPath, rootFile, fileSuffixFilters);
        return pathList;
    }

    private static void filePathAppend(List<String> filePaths, String rootPath, File dirFile, List<String> filters) {
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return;
        }

        File[] files = dirFile.listFiles();
        if (files == null) {
            return;
        }

        for (File file : files) {
            if (file.isFile()) {
                String fileSuffix = FileUtils.getFileSuffix(file.getName());
                if (filters == null) {
                    filePaths.add(file.getAbsolutePath().replace(rootPath, ""));
                } else if (filters.contains(fileSuffix)) {
                    filePaths.add(file.getAbsolutePath().replace(rootPath, ""));
                }
            } else if (file.isDirectory()) {
                filePathAppend(filePaths, rootPath, file, filters);
            }
        }
    }

    public static String getFileSuffix(String fileName) {
        int beginIndex = fileName.lastIndexOf(".");
        if (beginIndex == -1) {
            return "";
        }
        return fileName.substring(beginIndex);
    }
}
